package com.example.shiwu;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.shiwu.adapter.MyAdapter;
import com.example.shiwu.db.model.WifiListBean;
import com.example.shiwu.util.MySocket;
import com.example.shiwu.util.MyWifiManager;
import com.example.shiwu.util.PermissionsChecker;
import com.example.shiwu.util.SerialInter;
import com.example.shiwu.util.SerialManage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyJoinActivity extends AppCompatActivity implements SerialInter,AdapterView.OnItemSelectedListener{

    private Spinner spin_one;
    private Context mContext;
    private TextView outBtn;

    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private final int RESULT_CODE_LOCATION = 0x001;
    //定位权限,获取app内常用权限
    String[] permsLocation = {"android.permission.ACCESS_WIFI_STATE"
            , "android.permission.CHANGE_WIFI_STATE"
            , "android.permission.ACCESS_COARSE_LOCATION"
            , "android.permission.ACCESS_FINE_LOCATION"};

    RecyclerView recyclerView;
    Button btnGetWifi;
    MyAdapter adapter;
    private WifiManager mWifiManager;
    private List<ScanResult> mScanResultList;//wifi列表
    private List<WifiListBean> wifiListBeanList;
    private Dialog dialog;
    private View inflate;
    private MyJoinActivity.WifiBroadcastReceiver wifiReceiver;
    private TextView tv_wifiState;

    public TextView title_text,title_seting;
    public ImageView title_back;

    public RelativeLayout myWifi ,mySerialPort;

    public Socket mSocket;

    private SharedPreferences mSharedPreferences;
    private final int DEFAULT_PORT= 8086;
    private String mIpAddress;  //服务端ip地址
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";

    private OutputStream mOutStream;
    private InputStream mInStream;
    private SocketConnectThread mConnectThread;
    private SocketReceiveThread mReceiveThread;

    private HandlerThread mHandlerThread;
    //子线程中的Handler实例。
    private Handler mSubThreadHandler;

    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING= 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;

    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    private final String TAG = "MyJoinActivity";


    private ExecutorService mExecutorService = null;
    private PrintWriter printWriter;
    private BufferedReader in;
    private String receiveMsg;
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch(msg.what){
                case MSG_TIME_SEND:
                    break;
                case MSG_SOCKET_CONNECT:
                    mSocketConnectState = STATE_CONNECTED;
                    System.out.println(R.string.disconnect);
                    mReceiveThread = new SocketReceiveThread();
                    mReceiveThread.start();
                    break;
                case MSG_SOCKET_DISCONNECT:
                    System.out.println(R.string.connect);
                    mSocketConnectState = STATE_DISCONNECTED;
                    closeConnection();
                    break;
                case MSG_SOCKET_CONNECTFAIL:
                    mSocketConnectState = STATE_DISCONNECTED;
                    System.out.println("======================连接失败=========================");
                    break;
                case MSG_RECEIVE_DATA:
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiverWifi();//监听wifi变化

        if(mSocketConnectState == STATE_CONNECTED){
            System.out.println(R.string.state_connected);
        }else if(mSocketConnectState == STATE_DISCONNECTED){
            System.out.println(R.string.state_disconected);
        }
        else if(mSocketConnectState == STATE_CONNECTING){
            System.out.println(R.string.state_connected);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_join);
        mContext = MyJoinActivity.this;
        bindViews();
        myWifi = findViewById(R.id.my_wifi);
        mySerialPort = findViewById(R.id.my_serialPort);

        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_seting = findViewById(R.id.title_setting);

        title_text.setText("连接方式");
        title_seting.setVisibility(View.INVISIBLE);
        myWifi.setVisibility(View.GONE);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyJoinActivity.this.finish();
            }
        });

        if (mWifiManager == null) {
            mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        }
        getPerMission();//权限
        initView();//控件初始化
        initClickListener();//获取wifi
        setAdapter();//wifi列表

        mIpAddress = "192.168.4.1";
        //MySocket.instance().connect(mIpAddress,mClientPort);

    }

    private void bindViews() {
        spin_one = (Spinner) findViewById(R.id.spin_one);
        spin_one.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("spin_one111 ================================================================"+position);
        if(position == 0){
            myWifi.setVisibility(View.VISIBLE);
            mySerialPort.setVisibility(View.GONE);
            closeConnection();//关闭socket
        }
//        if(position == 1){
//            myWifi.setVisibility(View.VISIBLE);
//            mySerialPort.setVisibility(View.GONE);
//            //MySocket.getInstance(mContext);//wifi 模式下开启MySocket
//            //initHandlerThraed();
//
//        }else if(position == 0){
//            myWifi.setVisibility(View.GONE);
//            mySerialPort.setVisibility(View.VISIBLE);
//            closeConnection();//关闭socket
//
//           // SerialManage.getInstance().init(this);//串口初始化
//            //SerialManage.getInstance().open();//打开串口
//        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        System.out.println("spin_one ================================================================"+spin_one.getPopupContext());

    }

    //监听wifi变化
    public void registerReceiverWifi() {
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        registerReceiver(wifiReceiver, filter);
    }

    //setAdapter
    public void setAdapter() {
        //adapter = new MyAdapter(wifiListBeanList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter.setmOnItemClickListerer(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //连接wifi
                showCentreDialog(wifiListBeanList.get(position).getName(), position);
            }
        });
    }

    //获取权限
    public void getPerMission() {
        mPermissionsChecker = new PermissionsChecker(MyJoinActivity.this);
        if (mPermissionsChecker.lacksPermissions(permsLocation)) {
            ActivityCompat.requestPermissions(MyJoinActivity.this, permsLocation, RESULT_CODE_LOCATION);
        }
    }

    public void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        wifiListBeanList = new ArrayList<>();
        mScanResultList = new ArrayList<>();
    }

    public void initClickListener() {
        //获取wifi列表
        adapter = new MyAdapter(wifiListBeanList);
        wifiListBeanList.clear();

        //开启wifi
        MyWifiManager.openWifi(mWifiManager);
        //获取到wifi列表
        mScanResultList = MyWifiManager.getWifiList(mWifiManager);
        for (int i = 0; i < mScanResultList.size(); i++) {
            WifiListBean wifiListBean = new WifiListBean();
            wifiListBean.setName(mScanResultList.get(i).SSID);
            wifiListBean.setEncrypt(MyWifiManager.getEncrypt(mWifiManager, mScanResultList.get(i)));
            wifiListBeanList.add(wifiListBean);
        }

        if (wifiListBeanList.size() > 0) {
            adapter.notifyDataSetChanged();
            Toast.makeText(MyJoinActivity.this, "获取wifi列表成功", Toast.LENGTH_SHORT).show();
        } else {
            adapter.notifyDataSetChanged();
            Toast.makeText(MyJoinActivity.this, "wifi列表为空，请检查wifi页面是否有wifi存在", Toast.LENGTH_SHORT).show();
        }
    }

    //中间显示的dialog
    public void showCentreDialog(final String wifiName, final int position) {
        //自定义dialog显示布局
        inflate = LayoutInflater.from(MyJoinActivity.this).inflate(R.layout.dialog_centre, null);
        //自定义dialog显示风格
        dialog = new Dialog(MyJoinActivity.this, R.style.DialogCentre);
        //点击其他区域消失
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(inflate);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        wlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(wlp);
        dialog.show();
        TextView tvName, tvMargin;
        final EditText et_password;
        tvName = dialog.findViewById(R.id.tvName);
        tvMargin = dialog.findViewById(R.id.tvMargin);
        et_password = dialog.findViewById(R.id.et_password);

        tvName.setText("wifi：" + wifiName);
        tvMargin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                //MyWifiManager.disconnectNetwork(mWifiManager);//断开当前wifi
                String type = MyWifiManager.getEncrypt(mWifiManager, mScanResultList.get(position));//获取加密方式
                Log.e("=====连接wifi:", wifiName + "；加密方式" + type);
                MyWifiManager.connectWifi(mContext,mWifiManager, wifiName, et_password.getText().toString(), type);//连接wifi
                dialog.dismiss();

                SharedPreferences sp = mContext.getSharedPreferences(mContext.getPackageName(), Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                String ips = sp.getString("ip","");
                System.out.println("ips1 ================"+ips);
//                mIpAddress = "192.168.4.1";
//
                initHandlerThraed();//启动socket
                startConnect();
            }
        });
    }

    @Override
    public void connectMsg(String path, boolean isSucc) {
        String msg = isSucc ? "成功" : "失败";
        Log.e("串口连接回调", "串口 "+ path + " -连接" + msg);
    }

    @Override//若在串口开启的方法中 传入false 此处不会返回数据
    public void readData(String path, byte[] bytes, int size) {
//        Log.e("串口数据回调","串口 "+ path + " -获取数据" + bytes);
    }


    //监听wifi状态广播接收器
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                //wifi开关变化
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    case WifiManager.WIFI_STATE_DISABLED: {
                        //wifi关闭
                        Log.e("=====", "已经关闭");
                       // tv_wifiState.append("\n 打开变化：wifi已经关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        //wifi正在关闭
                        Log.e("=====", "正在关闭");
                        //tv_wifiState.append("\n 打开变化：wifi正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        //wifi已经打开
                        Log.e("=====", "已经打开");
                       // tv_wifiState.append("\n 打开变化：wifi已经打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        //wifi正在打开
                        Log.e("=====", "正在打开");
                        //tv_wifiState.append("\n 打开变化：wifi正在打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        //未知
                        Log.e("=====", "未知状态");
                        //tv_wifiState.append("\n 打开变化：wifi未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                //监听wifi连接状态
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.e("=====", "--NetworkInfo--" + info.toString());
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                    Log.e("=====", "wifi没连接上");
                    //tv_wifiState.append("\n 连接状态：wifi没连接上");
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                    Log.e("=====", "wifi以连接");
                    //tv_wifiState.append("\n 连接状态：wifi以连接，wifi名称：" + MyWifiManager.getWiFiName(mWifiManager));
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                    Log.e("=====", "wifi正在连接");
                    //tv_wifiState.append("\n 连接状态：wifi正在连接");
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                //监听wifi列表变化
                Log.e("=====", "wifi列表发生变化");
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //取消监听
        unregisterReceiver(wifiReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出HandlerThread的Looper循环。
        mHandlerThread.quit();
    }
    private void initHandlerThraed() {
        //创建HandlerThread实例
        mHandlerThread = new HandlerThread("handler_thread");
        //开始运行线程
        mHandlerThread.start();
        //获取HandlerThread线程中的Looper实例
        Looper loop = mHandlerThread.getLooper();
        //创建Handler与该线程绑定。
        mSubThreadHandler = new Handler(loop){
            public void handleMessage(Message msg) {
                Log.i(TAG, "mSubThreadHandler handleMessage thread:"+Thread.currentThread());
                switch(msg.what){
                    case MSG_SEND_DATA:
                        writeMsg((String)msg.obj);
                        break;
                    default:
                        break;
                }
            };
        };
    }
    private void writeMsg(String msg){
        Log.i(TAG, "writeMsg msg="+msg);
        if(msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void closeConnection(){
        try {
            if (mOutStream != null) {
                mOutStream.close(); //关闭输出流
                mOutStream = null;
            }
            if (mInStream != null) {
                mInStream.close(); //关闭输入流
                mInStream = null;
            }
            if(mSocket != null){
                mSocket.close();  //关闭socket
                mSocket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(mReceiveThread != null){
            mReceiveThread.threadExit();
            mReceiveThread = null;
        }
        mSocketConnectState = STATE_DISCONNECTED;
    }
    private void sendTxt(String str){
        if(mSocket == null){
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();
            return;
        }

        if(str.length() == 0)
            return;
        Message msg = new Message();
        msg.what = MSG_SEND_DATA;
        msg.obj = str;
        mSubThreadHandler.sendMessage(msg);
    }

    private void startConnect() {
        Log.i(TAG,"startConnect");
        if(mIpAddress == null || mIpAddress.length() == 0){
            Toast.makeText(this, "请设置ip地址", Toast.LENGTH_LONG).show();
            return;
        }
        if(mSocketConnectState != STATE_DISCONNECTED) return;
        mConnectThread = new SocketConnectThread();
        mConnectThread.start();
        mSocketConnectState = STATE_CONNECTING;
        System.out.println(R.string.state_connecting);
    }
    class SocketConnectThread extends Thread{
        public void run(){
            try {
                //连接服务端，指定服务端ip地址和端口号。
                mSocket = new Socket(mIpAddress,mClientPort);
                // 判断客户端和服务器是否连接成功
                System.out.println(mSocket.isConnected());
                if(mSocket != null){
                    //获取输出流、输入流
                    mOutStream = mSocket.getOutputStream();
                    mInStream = mSocket.getInputStream();
                    sendTxt("22,S;");
                    //sendTxt("13,update;");

                }
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
                return;
            }
            Log.i(TAG,"============================== connect success =====================");
            mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
        }

    }
    class SocketReceiveThread extends Thread{
        private boolean threadExit;
        public SocketReceiveThread() {
            threadExit = false;
        }
        public void run(){
            byte[] buffer = new byte[1024];
            while(threadExit == false){
                try {
                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    int count = mInStream.read(buffer);
                    if( count == -1){
                        Log.i(TAG, "read read -1");
                        mHandler.sendEmptyMessage(MSG_SOCKET_DISCONNECT);
                        break;
                    }else{
                        String receiveData = new String(buffer, 0, count);
                        Log.i(TAG, "read buffer:"+receiveData+",count="+count);
                        Message msg = new Message();
                        msg.what = MSG_RECEIVE_DATA;
                        msg.obj = receiveData;
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    System.out.println("+++++++++++++++ receive +++++++++++++++");

                    e.printStackTrace();
                }
            }
        }
        void threadExit(){
            threadExit = true;
        }
    }
}
